import json

import requests
from django.shortcuts import render, redirect
from django.contrib.auth.backends import ModelBackend
# 对密码加密、解密的工具
from django.contrib.auth.hashers import make_password, check_password
# 自定义用户验证字段
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.contrib.auth import get_user_model

User = get_user_model()
from django.db.models.query import QuerySet

import datetime

# 导入rest_framework的文件
import django_filters.rest_framework
from rest_framework import filters
from rest_framework import status
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework import generics
# 导入drf的许可
from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
import base64

# jwt生成token相关的信息
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler

# 导入model.py中的表格
from apps.resources.models import SubjectInfoModel
from apps.resources.models import LabelInfoModel
from apps.resources.models import QuestionTypeInfoModel
from apps.resources.models import QuestionLevelInfoModel
from apps.resources.models import QuestionInfoModel

# 导入serializers.py中的序列化类
from apps.resources.serializers import SubjectInfoSerializers
from apps.resources.serializers import LabelInfoSerializers
from apps.resources.serializers import QuestionTypeInfoSerializers
from apps.resources.serializers import QuestionLevelInfoSerializers
from apps.resources.serializers import QuestionInfoSerializers

# 导入paginations.py中的分页类
from apps.resources.paginations import SubjectInfoPagination
from apps.resources.paginations import LabelInfoPagination
from apps.resources.paginations import QuestionTypeInfoPagination
from apps.resources.paginations import QuestionLevelInfoPagination
from apps.resources.paginations import QuestionInfoPagination


# Create your views here.
# 学科信息视图集
class SubjectInfoViewset(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                         mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
        接口名称：\n
            学科信息视图集
        接口请求：\n
            api/resources/subject
        请求方式及权限：\n
            GET——list——AllowAny
            POST——create——AllowAny
            GET——retrieve——IsAuthenticated
            PUT/PATCH——update——IsAuthenticated
            DELETE——destroy——IsAuthenticated
    """
    queryset = SubjectInfoModel.objects.all().order_by('-id')
    serializer_class = SubjectInfoSerializers
    pagination_class = SubjectInfoPagination
    lookup_field = 'id'

    def get_queryset(self):
        queryset = self.queryset
        search_data = self.request.query_params.get('search_data', None)
        if search_data is not None:
            search_data = json.loads(search_data)
            queryset = SubjectInfoModel.objects.filter(**search_data).order_by('-id')
        return queryset


# 标签信息视图集
class LabelInfoViewset(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                       mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
        接口名称：\n
            标签信息视图集
        接口请求：\n
            api/resources/label
        请求方式及权限：\n
            GET——list——AllowAny
            POST——create——AllowAny
            GET——retrieve——IsAuthenticated
            PUT/PATCH——update——IsAuthenticated
            DELETE——destroy——IsAuthenticated
    """
    queryset = LabelInfoModel.objects.all().order_by('-id')
    serializer_class = LabelInfoSerializers
    pagination_class = LabelInfoPagination
    lookup_field = 'id'

    def get_queryset(self):
        queryset = self.queryset
        search_data = self.request.query_params.get('search_data', None)
        if search_data is not None:
            search_data = json.loads(search_data)
            if search_data.get('subject', None) is not None:
                search_data['subject'] = int(search_data['subject'])
            queryset = LabelInfoModel.objects.filter(**search_data).order_by('-id')
        return queryset


# 问题类型信息视图集
class QuestionTypeInfoViewset(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                              mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
        接口名称：\n
            问题类型信息视图集
        接口请求：\n
            api/resources/question-type
        请求方式及权限：\n
            GET——list——AllowAny
            POST——create——AllowAny
            GET——retrieve——IsAuthenticated
            PUT/PATCH——update——IsAuthenticated
            DELETE——destroy——IsAuthenticated
    """
    queryset = QuestionTypeInfoModel.objects.all().order_by('-type')
    serializer_class = QuestionTypeInfoSerializers
    pagination_class = QuestionTypeInfoPagination
    lookup_field = 'id'

    def get_queryset(self):
        queryset = self.queryset
        search_data = self.request.query_params.get('search_data', None)
        if search_data is not None:
            search_data = json.loads(search_data)
            try:
                if search_data.get('type', None) is not None:
                    # 防止int()输入值非数字
                    search_data['type'] = int(search_data['type'])
                queryset = QuestionTypeInfoModel.objects.filter(**search_data).order_by('-id')
            except ValueError:
                queryset = []
        return queryset


# 问题难度信息视图集
class QuestionLevelInfoViewset(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                               mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
        接口名称：\n
            问题难度信息视图集
        接口请求：\n
            api/resources/question-level
        请求方式及权限：\n
            GET——list——AllowAny
            POST——create——AllowAny
            GET——retrieve——IsAuthenticated
            PUT/PATCH——update——IsAuthenticated
            DELETE——destroy——IsAuthenticated
    """
    queryset = QuestionLevelInfoModel.objects.all().order_by('-level')
    serializer_class = QuestionLevelInfoSerializers
    pagination_class = QuestionLevelInfoPagination
    lookup_field = 'id'

    def get_queryset(self):
        queryset = self.queryset
        search_data = self.request.query_params.get('search_data', None)
        if search_data is not None:
            search_data = json.loads(search_data)
            try:
                if search_data.get('level', None) is not None:
                    # 防止int()输入值非数字
                    search_data['level'] = int(search_data['level'])
                queryset = QuestionLevelInfoModel.objects.filter(**search_data).order_by('-id')
            except ValueError:
                queryset = []
        return queryset


# 问题信息视图集
class QuestionInfoViewset(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin,
                          mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
        接口名称：\n
            问题信息视图集
        接口请求：\n
            api/resources/question
        请求方式及权限：\n
            GET——list——AllowAny
            POST——create——AllowAny
            GET——retrieve——IsAuthenticated
            PUT/PATCH——update——IsAuthenticated
            DELETE——destroy——IsAuthenticated
    """
    queryset = QuestionInfoModel.objects.all().order_by('-id')
    serializer_class = QuestionInfoSerializers
    pagination_class = QuestionInfoPagination
    lookup_field = 'id'

    def get_queryset(self):
        queryset = self.queryset
        search_data = self.request.query_params.get('search_data', None)
        if search_data is not None:
            search_data = json.loads(search_data)
            try:
                if search_data.get('subject', None) is not None:
                    search_data['subject'] = int(search_data['subject'])
                if search_data.get('label', None) is not None:
                    search_data['label'] = int(search_data['label'])
                if search_data.get('type', None) is not None:
                    # 防止int()输入值非数字
                    search_data['type'] = int(search_data['type'])
                if search_data.get('level', None) is not None:
                    # 防止int()输入值非数字
                    search_data['level'] = int(search_data['level'])
                queryset = QuestionInfoModel.objects.filter(**search_data).order_by('-id')
            except ValueError:
                queryset = []
        return queryset
